package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.business.mapper.WsdStudentsMapper;
import com.ruoyi.business.service.IWsdClassesService;
import com.ruoyi.business.service.IWsdParentsService;
import com.ruoyi.business.service.IWsdStudentsService;
import com.ruoyi.business.service.IWsdUserStudentService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.WsdStudentImportDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdClasses;
import com.ruoyi.common.core.domain.entity.WsdStudents;
import com.ruoyi.common.core.domain.entity.WsdUserStudent;
import com.ruoyi.common.core.domain.vo.WsdStudentImportVO;
import com.ruoyi.common.core.domain.vo.WsdStudentsChatINVO;
import com.ruoyi.common.core.domain.vo.studentInformationVO;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@Service
public class WsdStudentsServiceImpl extends ServiceImpl<WsdStudentsMapper, WsdStudents> implements IWsdStudentsService
{
    @Autowired
    private WsdStudentsMapper wsdStudentsMapper;
    @Autowired
    private IWsdParentsService wsdParentsService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IWsdUserStudentService wsdUserStudentService;
    @Autowired
    private IWsdClassesService wsdClassesService;
    /**
     * 查询学生信息
     *
     * @param id 学生信息主键
     * @return 学生信息
     */
    @Override
    public WsdStudents selectWsdStudentsById(Long id)
    {
        return wsdStudentsMapper.selectWsdStudentsById(id);
    }

    /**
     * 查询学生信息列表
     *
     * @param wsdStudents 学生信息
     * @return 学生信息
     */
    @Override
    public List<WsdStudents> selectWsdStudentsList(WsdStudents wsdStudents) {
        return wsdStudentsMapper.selectWsdStudentsList(wsdStudents);
    }

    /**
     * 新增学生信息
     *
     * @param wsdStudents 学生信息
     * @return 结果
     */
    @Override
    public int insertWsdStudents(WsdStudents wsdStudents)
    {
        wsdStudents.setCreateTime(DateUtils.getNowDate());
        //return wsdStudentsMapper.insertWsdStudents(wsdStudents);
        return wsdStudentsMapper.insert(wsdStudents);
    }
    @Override
    public int insertWsdStudents1(WsdStudents wsdStudents)
    {
        wsdStudents.setCreateTime(DateUtils.getNowDate());
        //return wsdStudentsMapper.insertWsdStudents(wsdStudents);
        try {
            wsdStudentsMapper.insert(wsdStudents);
        }catch (Exception e){
            return 0;
        }
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber( wsdStudents.getParentsPhone() );
        sysUser.setSchoolId(wsdStudents.getSchoolId());
        List<SysUser> list = userService.selectUserList(sysUser);
        if (list.size() > 0) {
            //家长已有账号，添加关系表
            WsdUserStudent wsdUserStudent = new WsdUserStudent();
            wsdUserStudent.setStudentId( wsdStudents.getId() );
            wsdUserStudent.setUserId( list.get( 0 ).getUserId() );
            return wsdUserStudentService.insertWsdUserStudent(wsdUserStudent);
        }else {
            //没有账号就新增
            sysUser.setStudentId( wsdStudents.getId() );
            sysUser.setNickName( "家长1" );
            sysUser.setUserName( wsdStudents.getParentsPhone() );
            //小程序用户11
            sysUser.setUserType( "11" );
            wsdParentsService.insertWsdParents(sysUser);
            //家长--学生，关系表
            WsdUserStudent wsdUserStudent = new WsdUserStudent();
            wsdUserStudent.setStudentId( wsdStudents.getId() );
            wsdUserStudent.setUserId( sysUser.getUserId() );
            return wsdUserStudentService.insertWsdUserStudent(wsdUserStudent);
        }
    }

    /**
     * 修改学生信息
     *
     * @param wsdStudents 学生信息
     * @return 结果
     */
    @Override
    public int updateWsdStudents(WsdStudents wsdStudents)
    {
        wsdStudents.setUpdateTime(DateUtils.getNowDate());
        return wsdStudentsMapper.updateWsdStudents(wsdStudents);
    }

    /**
     * 批量删除学生信息
     *
     * @param ids 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteWsdStudentsByIds(Long[] ids)
    {
        Integer i = wsdStudentsMapper.deleteWsdStudentsByIds(ids);
        if (i > 0) {
            //删除学生与家长关系表
            wsdUserStudentService.deleteWsdUserStudentSByIds(ids);
        }
        return i;
    }

    /**
     * 删除学生信息信息
     *
     * @param id 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteWsdStudentsById(Long id)
    {
        return wsdStudentsMapper.deleteWsdStudentsById(id);
    }

    /**
     * 获得学生的信息
     *
     * @param schoolId
     * @param phonenumber
     * @return
     */
    @Override
    public List<studentInformationVO> studentInformation(Long schoolId, Long studentId) {
        List<studentInformationVO> voList =  wsdStudentsMapper.studentInformation(schoolId,studentId);
        return voList;
    }

    /**
     * 获取学校人数
     *
     * @param classIds
     * @return
     */
    @Override
    public Long populationStatistics(Long[] classIds) {
        LambdaQueryWrapper<WsdStudents> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WsdStudents::getClassId,classIds);
        wrapper.eq(WsdStudents::getIsDeleted, Constants.STATUSONE);
        return this.count(wrapper);
    }

    /**
     * 导入学生
     * @param userList
     * @param classId
     * @param schoolId
     * @return
     */
    @Override
    public AjaxResult importData(List<WsdStudentImportDTO> userList,Long classId,Long schoolId) {
        //导入结果
        Integer success = 0;
        Integer failed = 0;
        //失败
        List<WsdStudentImportVO> failedList = new ArrayList<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        schoolId = user.getSchoolId();

        for (WsdStudentImportDTO wsdStudentImportDTO : userList){
            if (wsdStudentImportDTO.getIdentityNumber() == null||wsdStudentImportDTO.getIdentityNumber()==""){
                failed++;
                WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                String FailureResult = "导入失败-"+"身份证号为空/格式不正确";
                wsdStudentImportVO.setFailureResult( FailureResult );
                failedList.add( wsdStudentImportVO );
                continue;
            }
            if (wsdStudentImportDTO.getParentsPhone()==null||wsdStudentImportDTO.getParentsPhone()==""){
                failed++;
                WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                String FailureResult = "导入失败-"+"家长手机号为空/格式不正确";
                wsdStudentImportVO.setFailureResult( FailureResult );
                failedList.add( wsdStudentImportVO );
                continue;
            }
            if (wsdStudentImportDTO.getClassName()==null||wsdStudentImportDTO.getClassName()==""){
                failed++;
                WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                String FailureResult = "导入失败-"+"班级为空/格式不正确";
                wsdStudentImportVO.setFailureResult( FailureResult );
                failedList.add( wsdStudentImportVO );
                continue;
            }
            wsdStudentImportDTO.setClassName(wsdStudentImportDTO.getClassName().replaceAll("\\s", ""));
            wsdStudentImportDTO.setIdentityNumber(wsdStudentImportDTO.getIdentityNumber().replaceAll("\\s", ""));
            wsdStudentImportDTO.setParentsPhone(wsdStudentImportDTO.getParentsPhone().replaceAll("\\s", ""));
            WsdClasses wsdClasses = wsdClassesService.selectWsdClassesByName(wsdStudentImportDTO.getClassName(),schoolId);
            if (wsdClasses==null){
                failed++;
                WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                String FailureResult = "导入失败-"+"班级名称不正确";
                wsdStudentImportVO.setFailureResult( FailureResult );
                failedList.add( wsdStudentImportVO );
                continue;
            }
            //检查是否已经有这个学生
            WsdStudentsChatINVO chat = wsdStudentsMapper.selectWsdStudentsByIdentityNumber(wsdStudentImportDTO.getIdentityNumber() );
            if (chat!=null){//已有学生，更新数据
//                failed++;
//                WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
//                wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
//                wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
//                wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
//                wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
//                String FailureResult = "导入失败-"+"该学生身份证号已存在";
//                wsdStudentImportVO.setFailureResult( FailureResult );
//                failedList.add( wsdStudentImportVO );
//                continue;
                WsdStudents wsdStudents = new WsdStudents();
                wsdStudents.setId( chat.getId() );
                wsdStudents.setClassId( wsdClasses.getId() );
                wsdStudents.setSchoolId( wsdClasses.getSchoolId() );
                wsdStudents.setName( wsdStudentImportDTO.getName() );
                wsdStudents.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                int isSuccess = wsdStudentsMapper.updateWsdStudents( wsdStudents );
                if (isSuccess > 0) {
                    success++;
                    SysUser sysUser = new SysUser();
                    sysUser.setPhonenumber( wsdStudents.getParentsPhone() );
                    sysUser.setSchoolId( wsdStudents.getSchoolId() );
                    List<SysUser> list = userService.selectUserList( sysUser );
                    if (!list.isEmpty()){
                        //已有账号
                        //是否已有关系
                        WsdUserStudent wsdUserStudent1 = new WsdUserStudent();
                        wsdUserStudent1.setStudentId( wsdStudents.getId() );
                        wsdUserStudent1.setUserId( list.get( 0 ).getUserId() );
                        List<WsdUserStudent> wsdUserStudentList = wsdUserStudentService.selectWsdUserStudentList( wsdUserStudent1 );
                        if (wsdUserStudentList.isEmpty()){
                            //家长已有账号，添加关系表
                            WsdUserStudent wsdUserStudent = new WsdUserStudent();
                            wsdUserStudent.setStudentId( wsdStudents.getId() );
                            wsdUserStudent.setUserId( list.get( 0 ).getUserId() );
                            wsdUserStudentService.insertWsdUserStudent( wsdUserStudent );
                        }
                    }else {
                        //没有账号
                        sysUser.setStudentId( wsdStudents.getId() );
                        String name = wsdStudents.getName() + "家长";
                        sysUser.setNickName( name );
                        sysUser.setUserName( wsdStudents.getParentsPhone() );
                        //小程序用户11
                        sysUser.setUserType( "11" );
                        wsdParentsService.insertWsdParents( sysUser );
                        //家长--学生，关系表
                        WsdUserStudent wsdUserStudent = new WsdUserStudent();
                        wsdUserStudent.setStudentId( wsdStudents.getId() );
                        wsdUserStudent.setUserId( sysUser.getUserId() );
                        wsdUserStudentService.insertWsdUserStudent( wsdUserStudent );
                    }
                }else {
                    failed++;
                    WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                    wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                    wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                    wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                    wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                    wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                    wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                    String FailureResult = "导入失败";
                    wsdStudentImportVO.setFailureResult( FailureResult );
                    failedList.add( wsdStudentImportVO );
                }
            }else {//新增学生
                WsdStudents wsdStudents = new WsdStudents();
                wsdStudents.setClassId( wsdClasses.getId() );
                wsdStudents.setSchoolId( wsdClasses.getSchoolId() );
                wsdStudents.setName( wsdStudentImportDTO.getName() );
                if ("男".equals( wsdStudentImportDTO.getStudentsSex() )) {
                    wsdStudents.setStudentsSex( 0L );
                } else if ("女".equals( wsdStudentImportDTO.getStudentsSex() )) {
                    wsdStudents.setStudentsSex( 1L );
                }
                wsdStudents.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                wsdStudents.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                int isSuccess = wsdStudentsMapper.insertWsdStudents( wsdStudents );
                if (isSuccess > 0) {
                    success++;
                    SysUser sysUser = new SysUser();
                    sysUser.setPhonenumber( wsdStudents.getParentsPhone() );
                    sysUser.setSchoolId( wsdStudents.getSchoolId() );
                    List<SysUser> list = userService.selectUserList( sysUser );
                    if (list.size() > 0) {
                        //家长已有账号，添加关系表
                        WsdUserStudent wsdUserStudent = new WsdUserStudent();
                        wsdUserStudent.setStudentId( wsdStudents.getId() );
                        wsdUserStudent.setUserId( list.get( 0 ).getUserId() );
                        int i = wsdUserStudentService.insertWsdUserStudent( wsdUserStudent );
                    } else {
                        //没有账号就新增
                        sysUser.setStudentId( wsdStudents.getId() );
                        String name = wsdStudents.getName() + "家长";
                        sysUser.setNickName( name );
                        sysUser.setUserName( wsdStudents.getParentsPhone() );
                        //小程序用户11
                        sysUser.setUserType( "11" );
                        wsdParentsService.insertWsdParents( sysUser );
                        //家长--学生，关系表
                        WsdUserStudent wsdUserStudent = new WsdUserStudent();
                        wsdUserStudent.setStudentId( wsdStudents.getId() );
                        wsdUserStudent.setUserId( sysUser.getUserId() );
                        int i = wsdUserStudentService.insertWsdUserStudent( wsdUserStudent );
                    }
                } else {
                    failed++;
                    WsdStudentImportVO wsdStudentImportVO = new WsdStudentImportVO();
                    wsdStudentImportVO.setGradeName( wsdStudentImportDTO.getGradeName() );
                    wsdStudentImportVO.setClassName( wsdStudentImportDTO.getClassName() );
                    wsdStudentImportVO.setName( wsdStudentImportDTO.getName() );
                    wsdStudentImportVO.setStudentsSex( wsdStudentImportDTO.getStudentsSex() );
                    wsdStudentImportVO.setIdentityNumber( wsdStudentImportDTO.getIdentityNumber() );
                    wsdStudentImportVO.setParentsPhone( wsdStudentImportDTO.getParentsPhone() );
                    String FailureResult = "导入失败";
                    wsdStudentImportVO.setFailureResult( FailureResult );
                    failedList.add( wsdStudentImportVO );
                }
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put( "successCount", success );
        resultMap.put( "errorCount" , failed);
        resultMap.put("result", failedList);
        AjaxResult result = AjaxResult.success();
        result.put("data",resultMap); // 或者根据框架要求，可能需要直接返回jsonResult
        return result;
    }
}
